//
//  WTHttpRequest.m
//  AI
//
//  Created by awifi on 8/1/18.
//  Copyright © 2018年 zjhc. All rights reserved.
//

#import "WTHttpRequest.h"
#import "AFNetworking.h"
#import "UrlManage.h"

@implementation WTHttpRequest
+(void)requestJsonPostWithUrlStr:(NSString*)urlStr params:(NSDictionary*)params onComplete:(void (^)(NSError* error,NSDictionary* resultJson))onComplete{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    AFHTTPSessionManager*manager=[AFHTTPSessionManager manager];
    
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];

    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"content-type"];
    [manager.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    
    //    [manager.requestSerializer setValue:[NSUserDefaultsUtil gettoken] forHTTPHeaderField:@"token"];
    
    
    __block NSDictionary*resultJson=nil;
    __block NSError*error=nil;
    NSString*urlString=[NSString stringWithFormat:@"%@%@",[UrlManage sharedManager].baseUrl,urlStr];
    NSMutableDictionary * dict = [NSMutableDictionary dictionaryWithDictionary:params];
    
    [manager POST:urlString parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //请求成功
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        NSString * code=[responseObject objectForKey:@"code"];
        
        if ([code isKindOfClass:[NSNull class]]) {
            
            NSString* errorReason =@"请求数据为空";
            error=[NSError errorWithDomain:errorReason code:1 userInfo:nil];
            
        }else{
            
            //E00000001
            if (![code isEqualToString:@"0"]){
                NSString*errorMsg=[responseObject objectForKey:@"msg"];
                if ([errorMsg isKindOfClass:[NSNull class]] || [errorMsg isEqualToString:@""]) {
                    errorMsg = @"服务器正在闹脾气";
                }
                error= [NSError errorWithDomain:errorMsg code:1 userInfo:nil];
            }else
                resultJson = responseObject;
        }
        onComplete(error,resultJson);//可以直接将msg传出去  这样做多余了。
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //请求失败
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        long code=(long)error.code;
        NSLog(@"error1:%@",error);
        if ([error.domain isEqualToString:NSURLErrorDomain])
            code= (code==-1001)?-2:-1;
        error=[NSError errorWithDomain:error.domain code:code userInfo:nil];
        onComplete(error,resultJson);
    }];
}
+(void)requestMultipartFileJsonPostWithUrlStr:(NSString*)urlStr params:(NSDictionary*)params onComplete:(void (^)(NSError* error,NSDictionary* resultJson))onComplete{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

    //创建会话管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    manager.requestSerializer = [AFJSONRequestSerializer serializer];
//    manager.responseSerializer = [AFJSONResponseSerializer serializer];
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
//
//    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"content-type"];
//    [manager.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    //发送post请求上传路径
    /*
     第一个参数:请求路径
     第二个参数:字典(非文件参数)
     第三个参数:constructingBodyWithBlock 处理要上传的文件数据
     第四个参数:进度回调
     第五个参数:成功回调 responseObject响应体信息
     第六个参数:失败回调
     */
    NSString * urlString = [NSString stringWithFormat:@"http://192.168.212.228:80/%@?access_token=%@",urlStr,[NSUserDefaultsUtil gettoken]];
    __block NSDictionary*resultJson=nil;
    __block NSError*error=nil;
    [manager POST:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
//        NSURL *imageUrl = [NSURL URLWithString:@"file:///Users/abc/Desktop/image.png"];

        NSString *pathUrl = [params objectForKey:@"path"];
        //1.创建录音文件存放路径
        NSString * path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.pcm",pathUrl]];
      
        
        //方法三:
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:path] name:[NSString stringWithFormat:@"%@.pcm",pathUrl] error:nil];
        
    }
         progress:^(NSProgress * _Nonnull uploadProgress) {
             
             NSLog(@"%f",1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
             
         }
          success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
              [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

              NSLog(@"上传成功.%@",responseObject);
              NSString * code=[responseObject objectForKey:@"code"];
              if(![code isEqualToString:@"0"]){
                  NSString*errorMsg=[responseObject objectForKey:@"msg"];
                  if ([errorMsg isKindOfClass:[NSNull class]] || [errorMsg isEqualToString:@""]) {
                      errorMsg = @"服务器正在闹脾气";
                  }
                  error= [NSError errorWithDomain:errorMsg code:1 userInfo:nil];
              }else
              {
                  resultJson = responseObject;

              }
              onComplete(error,responseObject);
          }
          failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
              [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

              long code=(long)error.code;
              NSLog(@"error1:%@",error);
              if ([error.domain isEqualToString:NSURLErrorDomain])
              code= (code==-1001)?-2:-1;
              error=[NSError errorWithDomain:error.domain code:code userInfo:nil];
              onComplete(error,resultJson);
              NSLog(@"上传失败.%@",error);
          }];
}

//Get请求
+(void)requestJsonGetWithUrlStr:(NSString *)urlStr params:(NSDictionary*)params onComplete:(void (^)(NSError* error,NSDictionary* resultJson))onComplete{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    AFHTTPSessionManager*manager=[AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"content-type"];
    [manager.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    __block NSDictionary*resultJson=nil;
    __block NSError*error=nil;
//      NSString*urlString=[NSString stringWithFormat:@"%@%@",[UrlManage sharedManager].baseUrl,urlStr];
    NSString*urlString=[NSString stringWithFormat:@"%@%@?access_token=%@",[UrlManage sharedManager].baseUrl,urlStr,[NSUserDefaultsUtil gettoken]];
    [manager.requestSerializer setValue:[NSUserDefaultsUtil gettoken] forHTTPHeaderField:@"token"];
    NSMutableDictionary *  dict = [NSMutableDictionary dictionary];
    NSString *str =  [HXNSStringUtil getJsonStringFromDicOrArray:params];
    [dict setObject:str forKey:@"params"];
    [manager GET:urlString parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //请求成功
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        resultJson=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSString * code=[resultJson objectForKey:@"code"];
        if ([code isKindOfClass:[NSNull class]]) {
            
            NSString* errorReason =@"请求数据为空";
            error=[NSError errorWithDomain:errorReason code:1 userInfo:nil];
            
        }else{
            if ([code isEqualToString:@"100"]) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"LoginOutRefresh" object:nil];
                return;
            }
            //E00000001
            if (![code isEqualToString:@"0"]  && ![urlStr isEqualToString:@"/userservice/photocode"]){
                
                NSString*errorMsg=[resultJson objectForKey:@"msg"];
                if ([errorMsg isKindOfClass:[NSNull class]] || [errorMsg isEqualToString:@""]) {
                    errorMsg = @"服务器正在闹脾气";
                }
                error= [NSError errorWithDomain:errorMsg code:1 userInfo:nil];
            }else
                resultJson = resultJson;
        }
        //        int flag=[[resultJson objectForKey:@"flag"] intValue];
        //        int code=[[resultJson objectForKey:@"errorCode"] intValue];
        //        if (flag!=SUCCESS|code!=10000){
        //            error= [NSError errorWithDomain:@"" code:code userInfo:nil];
        //            NSLog(@"request url:%@\n error:%@",urlString,error);
        //        }else
        onComplete(error,resultJson);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //请求失败
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        long code=(long)error.code;
        NSLog(@"error1:%@",error);
        if ([error.domain isEqualToString:NSURLErrorDomain])
            code= (code==-1001)?-2:-1;
        error=[NSError errorWithDomain:error.domain code:code userInfo:nil];
        onComplete(error,resultJson);
    }];
    
}
    +(void)requestJsonPutWithUrlStr:(NSString*)urlStr params:(NSDictionary*)params onComplete:(void (^)(NSError* error,NSDictionary* resultJson))onComplete{
        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
        AFHTTPSessionManager*manager=[AFHTTPSessionManager manager];
        
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
        
        [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"content-type"];
        [manager.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        
        //    [manager.requestSerializer setValue:[NSUserDefaultsUtil gettoken] forHTTPHeaderField:@"token"];
        
        
        __block NSDictionary*resultJson=nil;
        __block NSError*error=nil;
        NSString*urlString=[NSString stringWithFormat:@"%@%@",[UrlManage sharedManager].baseUrl,urlStr];
        NSMutableDictionary * dict = [NSMutableDictionary dictionaryWithDictionary:params];
        
        [manager PUT:urlString parameters:dict success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            //请求成功
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            NSString * code=[responseObject objectForKey:@"code"];
            
            if ([code isKindOfClass:[NSNull class]]) {
                
                NSString* errorReason =@"请求数据为空";
                error=[NSError errorWithDomain:errorReason code:1 userInfo:nil];
                
            }else{
                
                //E00000001
                if (![code isEqualToString:@"0"]){
                    NSString*errorMsg=[responseObject objectForKey:@"msg"];
                    if ([errorMsg isKindOfClass:[NSNull class]] || [errorMsg isEqualToString:@""]) {
                        errorMsg = @"服务器正在闹脾气";
                    }
                    error= [NSError errorWithDomain:errorMsg code:1 userInfo:nil];
                }else
                    resultJson = responseObject;
            }
            onComplete(error,resultJson);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            //请求失败
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            long code=(long)error.code;
            NSLog(@"error1:%@",error);
            if ([error.domain isEqualToString:NSURLErrorDomain])
                code= (code==-1001)?-2:-1;
            error=[NSError errorWithDomain:error.domain code:code userInfo:nil];
            onComplete(error,resultJson);
        }];
    }

//Get请求
+(void)requestAuthCodeGetWithUrlStr:(NSString *)urlStr params:(NSDictionary*)params onComplete:(void (^)(NSError* error,NSDictionary* resultJson))onComplete{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    AFHTTPSessionManager*manager=[AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"content-type"];
    [manager.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    __block NSDictionary*resultJson=nil;
    __block NSError*error=nil;
    NSString*urlString=[NSString stringWithFormat:@"%@%@",[UrlManage sharedManager].baseUrl,urlStr];
//    __block __weak WTHttpRequest *request = self;
    [manager GET:urlString parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //请求成功
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        UIImage *image1 = [UIImage imageWithData:responseObject];
        // 将NSData转为UIImage
        NSMutableDictionary *dict =[NSMutableDictionary dictionaryWithObjectsAndKeys:image1,@"image", nil];
        resultJson = (NSDictionary *)dict;
        
        onComplete(error,resultJson);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //请求失败
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        long code=(long)error.code;
        NSLog(@"error1:%@",error);
        if ([error.domain isEqualToString:NSURLErrorDomain])
            code= (code==-1001)?-2:-1;
        error=[NSError errorWithDomain:error.domain code:code userInfo:nil];
        onComplete(error,resultJson);
    }];
    
}

- (UIImage *)decodeBase64ToImage:(NSString *)strEncodeData {
    NSData *data = [[NSData alloc]initWithBase64EncodedString:strEncodeData options:NSDataBase64DecodingIgnoreUnknownCharacters];
    return [UIImage imageWithData:data];
}

@end
